package com.aiyige.base.api.httpinterceptor;

import android.os.Build;
import android.util.Base64;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.base.api.ApiUrls;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class AuthTokenInterceptor implements Interceptor {
    String clientInfo = "";

    public AuthTokenInterceptor() {
        try {
            clientInfo = Base64.encodeToString((BuildConfig.AIYIGE_CLIENT_ID + ":" + BuildConfig.AIYIGE_CLIENT_SECRET).getBytes("UTF-8"), Base64.NO_WRAP | Base64.URL_SAFE);
        } catch (UnsupportedEncodingException e) {
            clientInfo = "";
        }
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        boolean shouldAddAuthorization = request.url().toString().contains("oauth/token");
        HttpUrl.Builder httpUrlBuilder = request.url().newBuilder();
        Request.Builder requestBuilder = request.newBuilder();
        Request newRequest;
        try {
            if (AccountUtil.isLogin()) {
                httpUrlBuilder.setQueryParameter("access_token", AccountUtil.getCurrentUser().getAccessToken().getAccess_token());
                requestBuilder.addHeader("clientInfo", "Basic " + clientInfo);
                if (shouldAddAuthorization) {
                    requestBuilder.addHeader("Authorization", "Basic " + clientInfo);
                }
                newRequest = requestBuilder.url(httpUrlBuilder.build()).build();
            } else {
                httpUrlBuilder.setQueryParameter("access_token", BuildConfig.GUEST_ACCESS_TOKEN);
                requestBuilder.addHeader("clientInfo", "Basic " + clientInfo);
                if (shouldAddAuthorization) {
                    requestBuilder.addHeader("Authorization", "Basic " + clientInfo);
                }
                newRequest = requestBuilder.url(httpUrlBuilder.build()).build();
            }
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
        return chain.proceed(newRequest);
    }
}
